<template>
  <div>
    <!-- 面包屑导航区 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 卡片视图 -->
       <el-card>
          <el-row>
            <el-col :span="8">
               <el-input placeholder="请输入内容" v-model="userQueryInfo.query" clearable @clear="getUserList">
                <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
              </el-input>
            </el-col>
            <el-col :span="16">
              <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
            </el-col>
          </el-row>

          <el-table :data="userList" border stripe>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="姓名" prop="username"></el-table-column>
            <el-table-column label="邮箱" prop="email"></el-table-column>
            <el-table-column label="电话" prop="mobile"></el-table-column>
            <el-table-column label="角色" prop="role_name"></el-table-column>
            <el-table-column label="状态">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.mg_state" @change="changeStatus(scope.row)"></el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="editUser(scope.row)"></el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteUser(scope.row.id)"></el-button>
                <el-button size="mini" type="warning" icon="el-icon-setting" @click="setRoles(scope.row)"></el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页区域 -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="userQueryInfo.pagenum"
              :page-sizes="[1, 2, 5, 10]"
              :page-size="userQueryInfo.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
          </el-pagination>
       </el-card>
       <!--  添加用户对话框 -->
       <el-dialog
          title="添加用户"
          :visible.sync="addDialogVisible"
          width="50%"
          @close="addUserClosed"
          >
          <el-form ref="addFormRef" :rules="addUserRules" :model="addFormInfo" label-width="80px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="addFormInfo.username"></el-input>
            </el-form-item>
            <el-form-item label="密码"  prop="password">
              <el-input v-model="addFormInfo.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱"  prop="email">
              <el-input v-model="addFormInfo.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="addFormInfo.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="toAddUser">确 定</el-button>
          </span>
        </el-dialog>
        <!--  编辑用户对话框 -->
        <el-dialog
          title="编辑用户"
          :visible.sync="editDialogVisible"
          width="50%"
          >
          <el-form ref="editFormRef" :rules="editUserRules" :model="editFormInfo" label-width="80px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="editFormInfo.username"></el-input>
            </el-form-item>
            <el-form-item label="邮箱"  prop="email">
              <el-input v-model="editFormInfo.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="editFormInfo.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="toEditUser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 分配角色对话框 -->
        <el-dialog
          title="分配角色"
          :visible.sync="setRolesDialogVisible"
          width="50%"
          @close="setRolesClosed"
          >
          <p>当前的用户：{{userInfo.username }}</p>
          <p>当前的角色：{{userInfo.role_name }}</p>
          分配角色：
            <el-select v-model="selectRoleId" placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>

          <span slot="footer" class="dialog-footer">
            <el-button @click="setRolesDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="toSetRole">确 定</el-button>
          </span>
        </el-dialog>
  </div>
</template>

<script>
import { Select } from 'element-ui';


export default {
  created() {
    this.getUserList()
    
  },
  data() {
    var checkEmail = (rule,value,cb)=>{
      const emailRegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
      if(emailRegex.test(value)){
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }

    var checkMobile = (rule,value,cb)=>{
      const mobileRegex = /^1[3-9]\d{9}$/;
      if(mobileRegex.test(value)){
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }

    return {
      userList:[],
      userQueryInfo:{
        query:'',
        pagenum:1,
        pagesize:10
      },
      total:1,
      addDialogVisible:false,
      editDialogVisible:false,
      addFormInfo:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      addUserRules:{
        username:[{ required: true, message: '请输入用户名', trigger: 'blur' },],
        password:[{ required: true, message: '请输入密码', trigger: 'blur' },
                 { min: 3, max: 15, message: '长度在 3 到 5 个字符', trigger: 'blur' }],
        email:[{ validator: checkEmail, trigger: 'blur' }],
        mobile:[{ validator: checkMobile, trigger: 'blur' }]
      },
      editUserRules:{
        username:[{ required: true, message: '请输入用户名', trigger: 'blur' },],
        email:[{ validator: checkEmail, trigger: 'blur' }],
        mobile:[{ validator: checkMobile, trigger: 'blur' }]
      },
      editFormInfo:{},
      setRolesDialogVisible:false,
      userInfo:{},
      roleList:[],
      selectRoleId:''
      
    }
  },
  methods: {
     async getUserList(){
     const {data : res} = await this.$http.get('users',{params:this.userQueryInfo})
     if(res.meta.status !== 200){
      this.$message.error('获取用户列表失败')
     }
     this.userList = res.data.users
     this.total = res.data.total
    },
    handleSizeChange(newSize){
      this.userQueryInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newNum){
      this.userQueryInfo.pagenum = newNum
      this.getUserList()
    },
    async changeStatus(userInfo){
     
      const {data : res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if(res.meta.status !== 200){
        this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
      this.getUserList()
      
      
    },
    addUserClosed(){
      this.$refs.addFormRef.resetFields()
    },
    toAddUser(){
      this.$refs.addFormRef.validate(async valid =>{
        if(!valid) return 
        const {data : res} = await this.$http.post('users',this.addFormInfo)
        if(res.meta.status !== 200){
          this.$message.error('添加用户失败')
        }
        this.$message.success("添加用户成功")
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    editUser(userInfo){
      this.editFormInfo = userInfo
      this.editDialogVisible = true
    },
    toEditUser(){
        this.$refs.editFormRef.validate(async valid =>{
        if(!valid) return 
        const {data : res} = await this.$http.put(`users/${this.editFormInfo.id}`,{
            email:this.editFormInfo.email,
            mobile:this.editFormInfo.mobile
          })
          if(res.meta.status !== 200){
            return this.$message.error('更新用户失败')
          }
           this.$message.success('更新用户成功')
           this.editDialogVisible = false
      })
      
    },
    // 删除用户
    async deleteUser(uid){
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
      if(confirmResult !=='confirm'){
        return this.$message.info('已取消删除')
      }
       const {data : res} = await this.$http.delete(`users/${uid}`)
       if(res.meta.status !== 200){
        this.$message.error('删除失败')
       }
       this.$message.success('删除成功')
       this.getUserList()
    },
    async setRoles(userInfo){
      this.userInfo = userInfo
      const{data : res} = await this.$http.get('roles')
      this.roleList = res.data
      this.setRolesDialogVisible = true
    },
    async toSetRole(){
      if(!this.selectRoleId){
        return this.$message.error('请分配角色')
      }
    const{data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,{
        rid:this.selectRoleId
      })
    if(res.meta.status !== 200){
      return this.$message.error('分配角色失败')
    }
      this.$message.success('更新角色成功')
      this.setRolesDialogVisible = false
      this.getUserList()
    },
    setRolesClosed(){
      this.selectRoleId = ''
    }
  },

}
</script>

<style lang="less" scoped>

.el-button{
  margin-left: 20px;
}

</style>